package com.ubing.gxspringboot;

import com.ubing.gxspringboot.gxapplicationcontext.GXWebApplicationContext;
import com.ubing.gxspringboot.gxservlet.GXDispatcherServlet;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

public class GXSpringApplication {
    static public void run(Class clazz){
        GXWebApplicationContext gxWebApplicationContext = new GXWebApplicationContext();
        gxWebApplicationContext.init(clazz);
        startTomcat(gxWebApplicationContext);
    }

    private static void startTomcat(GXWebApplicationContext gxWebApplicationContext) {
        Tomcat tomcat=new Tomcat();
        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");
        Connector connector = new Connector();
        connector.setPort(8088);
        StandardEngine engine = new StandardEngine();
        engine.setDefaultHost("localhost");

        StandardHost host = new StandardHost();
        host.setName("localhost");

        String contextPath="";
        StandardContext context = new StandardContext();

        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(context);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);

        tomcat.addServlet(contextPath,"dispatcher", new GXDispatcherServlet(gxWebApplicationContext));
        context.addServletMappingDecoded("/*","dispatcher");

        try {
            tomcat.start();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
    }
}
